<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#div1 {
				width: 100px;
				height: 100px;
				border: 1px solid green;
                                                                    background: green;
				position: absolute;
			}
		</style>

		<script >
			window.onload = function() {

				var speed = 10;
				var dir = 0;
				//设置速度
				setInterval(function() {


					switch (dir) {
						case 38:
							console.log(div1.offsetTop)
							div1.style.top = div1.offsetTop - speed + "px";
							break;
						case 40:
							div1.style.top = div1.offsetTop + speed + "px";
							break;
						case 37:
							div1.style.left = div1.offsetLeft - speed + "px";
							break;
						case 39:
							div1.style.left = div1.offsetLeft + speed + "px";
							break;

					}

				}, 30)
              //键盘按下移动
				document.onkeydown = function(event) {
					var div1 = document.getElementById("div1");
					
					//传递方向
					 dir = event.keyCode;
					
				}
				//键盘抬起停止
				document.onkeyup=function(){
					dir=0;
				}
			}
		</script>
	</head>
	<body>
		<div id="div1"></div>
	</body>
</html>

